<?php
namespace WXAPI\Logic;
use Think\Model\RelationModel;
use WXAPI\Logic\WxsendLogic;
/**
 * 购物车 逻辑定义 
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic extends RelationModel
{
    /**
     * 加入购物车方法
     * @param type $goods_id  商品id
     * @param type $goods_num   商品数量
     * @param type $goods_spec  选择规格 
     * @param type $user_id 用户id
     */
    function addCart($goods_id,$goods_num,$goods_spec,$session_id,$user_id = 1,$ms_id,$is_pint,$pint_id)
    {       
    	$goods = M('Goods')->where("goods_id = $goods_id and is_on_sale=1 and is_delete=0 and goods_state=1")->find(); // 找出这个商品
    	if(empty($goods)){
    	    	return array('status'=>-4,'msg'=>'商品已经下架','result'=>'');
    	}
        $blacklist = M('blacklist')->where(['store_id'=>$goods['store_id'],'user_id'=>$user_id])->find();
    	if($blacklist){
            return array('status'=>-4,'msg'=>'商品已经下架','result'=>'');
        }
    	$store = M('store')->where(['store_id'=>$goods['store_id']])->find();
    	if($store && !$store['store_state']){
            return array('status'=>-4,'msg'=>'商品已经下架','result'=>'');
        }
        //处理规格名 key_name 没有的就自动添加  by sofwu start
        $keyName = M('spec_goods_price')->where(['key'=>implode('_',$goods_spec)])->getField('key_name');
        if(!$keyName){
            $specItem=[];
            foreach ($goods_spec as $item){
                $itemName = M('spec_item')->field('a.item,b.name')->alias('a')->join('ty_spec b on a.spec_id=b.id')->where(['a.id'=>$item])->find();
                $specItem[] = $itemName['name'].':'.$itemName['item'];
            }
            $specItemStr = join(' ',$specItem);
            M('spec_goods_price')->where(['key'=>implode('_',$goods_spec),'goods_id'=>$goods_id,'store_id'=>$goods['store_id']])->save(['key_name'=>$specItemStr]);
        }
        //处理规格名 key_name 没有的就自动添加  by sofwu end

    	$specGoodsPriceList = M('spec_goods_price')->where("goods_id = $goods_id and store_id=".$goods['store_id'])->getField("key,key_name,price,store_count,sku"); // 获取商品对应的规格价钱 库存 条码 

    	$where = " ";
    	$user_id = $user_id ? $user_id : 0;
		$discount=1;
    	if($user_id){
			$where .= " user_id= $user_id ";
			$users_fenbu = M('users')->where('user_id='.$user_id)->getField('fenbu_id');
			$user = M('users')->where("user_id = {$user_id}")->cache(true,TPSHOP_CACHE_TIME)->find();
			$discount=$user['discount'];
		}
    		
    		$catr_count = M('Cart')->where($where)->count(); // 查找购物车商品总数量
   //  		if($catr_count >= 30){
   //  			return array('status'=>-9,'msg'=>'购物车最多只能放30种商品','result'=>'');
			// }
    		if(!empty($specGoodsPriceList) && empty($goods_spec)){ // 有商品规格 但是前台没有传递过来
    			return array('status'=>-1,'msg'=>'必须传递商品规格','result'=>'');
			}
    		if($goods_num <= 0){
				return array('status'=>-2,'msg'=>'购买商品数量不能为0','result'=>'');
			}
    		if(empty($goods)){
    			return array('status'=>-3,'msg'=>'购买商品不存在','result'=>'');
			}
    		if(($goods['store_count'] < $goods_num)){
    			return array('status'=>-4,'msg'=>'商品库存不足','result'=>'');
			}
    		if($goods['prom_type'] > 0 && $user_id == 0){
    			return array('status'=>-101,'msg'=>'购买活动商品必须先登录','result'=>'');
			}
			
            if(!empty($goods_id)){
                $goodsData = M('goods')->where(['goods_id'=>$goods_id])->find();
                if(!empty($goodsData)){
                    //获取活动id
                    if($goodsData['prom_id'] != 0){
                        $promGoods = M('prom_goods')->where(['id'=>$goodsData['prom_id']])->find();
                        // $aa = $promGoods;
                        $time = time();
                        //活动存在而且开始了
                        if($promGoods['start_time'] < $time && $promGoods['end_time'] >$time){//活动期间
                            $promSpec = json_decode($promGoods['goods_key'],true);
                                if($goods_num != 0 && $promGoods['xiangou'] !=0){
                                    if(in_array($spec,$promSpec) && $goods_num > $promGoods['xiangou']){
                                        return array('status'=>-4,'msg'=>'这个规格限制购买数量','result'=>'');
                                    }
                                }
                        }
                    }
                }
            }

				/* 规格判断货品是否充足 */
				if(!empty($goods_spec)){
					sort($goods_spec);
					$spec_key = implode('_', $goods_spec);
					if($specGoodsPriceList[$spec_key]['store_count'] < $goods_num){
						return array('status'=>-4,'msg'=>'商品库存不足','result'=>'');
					}
					$spec_price = $specGoodsPriceList[$spec_key]['price']; // 获取规格指定的价格
				}
    		$where .= " and goods_id = $goods_id and spec_key = '$spec_key' "; // 查询购物车是否已经存在这商品
 
    // 			$where .= " and  session_id = '$session_id' and session_id != ''";
				

    			$catr_goods = M('Cart')->where($where)->find(); // 查找购物车是否已经存在该商品
               
    			$price = $spec_price ? $spec_price : $goods['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
				$price=$price*$goods['floating']/100*$discount;
				$goods['prom_msg']='';
    			// 商品参与促销
    			if($goods['prom_id'] > 0)
    			{
    				$prom = get_goods_promotion($goods_id,$user_id,$price,$spec_key); //shadow
    				$price = $prom['price'];
					$goods['prom_msg'] = $prom['prom_msg'];
    				$goods['prom_type'] = $prom['prom_type'];
    				$goods['prom_id']   = $prom['prom_id'];
    			}

    			$data = array(
    				'user_id'         => $user_id,   // 用户id
    				'session_id'      => $session_id,   // sessionid
    				'goods_id'        => $goods_id,   // 商品id
    				'goods_sn'        => $goods['goods_sn'],   // 商品货号
    				'goods_name'      => $goods['goods_name'],   // 商品名称
    				'market_price'    => $goods['market_price'],   // 市场价
    				'goods_price'     => \sanwei($price),  // 购买价
    				'member_goods_price' => \sanwei($price),  // 会员折扣价 默认为 购买价
    				'goods_num'       => $goods_num, // 购买数量
    				'spec_key'        => "{$spec_key}", // 规格key
    				'spec_key_name'   => "{$specGoodsPriceList[$spec_key]['key_name']}", // 规格 key_name
    				'sku'        => "{$specGoodsPriceList[$spec_key]['sku']}", // 商品条形码
    				'add_time'        => time(), // 加入购物车时间
    				'prom_type'       => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠, 4 秒杀商品,101 拼团
    				'prom_id'         => $goods['prom_id'],   // 活动id
					'prom_msg'         => $goods['prom_msg'],
					'yijia'         => \sanwei(yj_price($goods['goods_id'],\sanwei($price),$users_fenbu))
    			);
    	       // dump($catr_goods);
    			// 如果商品购物车已经存在
    			if($catr_goods) 
    			{
    				// 如果购物车的已有数量加上 这次要购买的数量  大于  库存输  则不再增加数量
    				if(($catr_goods['goods_num'] + $goods_num) > $goods['store_count'])
    				$goods_num = 0;
    				$result = M('Cart')->where("id =".$catr_goods[id])->save(array("goods_num"=> ($catr_goods['goods_num'] + $goods_num)) ); // 数量相加
    				$cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
    				setcookie('cn',$cart_count,null,'/');
    				return array('status'=>1,'msg'=>'成功加入购物车','result'=>$cart_count,'shopExist'=>1);
    			}else
    			{
    				$store_id = M('goods')->where(array("goods_id"=>$goods_id))->getField('store_id');
    				$data['store_id'] = $store_id;
    				$insert_id = M('Cart')->add($data);
    				// dump($insert_id);
    				$cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
    				setcookie('cn',$cart_count,null,'/');
    				return array('status'=>1,'msg'=>'成功加入购物车','result'=>$cart_count,'shopExist'=>0);
    			}
    			$cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
    			return array('status'=>-5,'msg'=>'加入购物车失败','result'=>$cart_count);
    											
    											
    }


    /**
     * 购物车列表 
     * @param type $user   用户
     * @param type $session_id  session_id
     * @param type $selected  是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * $mode 0  返回数组形式  1 直接返回result
     */
    function cartList($user = array() , $session_id = '', $selected = 0,$mode =0)
    {
        
        $where = " 1 = 1 ";
        //if($selected != NULL)
        //    $where = " selected = $selected "; // 购物车选中状态
        
        if($user[user_id])// 如果用户已经登录则按照用户id查询
        {
             $where .= " and user_id = $user[user_id] ";
             // 给用户计算会员价 登录前后不一样             
        }           
        else
        {
            $where .= " and session_id = '$session_id'";
            $user[user_id] = 0;
        }
              
        
        //$cartList = M('Cart')->where($where)->order('store_id asc')->select();  // 获取购物车商品 
		$cartList = M('Cart')
		->alias('a')
		->join('ty_goods b on a.goods_id=b.goods_id')
		->where(array('b.is_on_sale'=>1,'b.goods_state'=>1,'b.is_delete'=>0))
		->where($where)->select();
        $anum = $total_price =  $cut_fee = $original_fee = 0;

        //优惠详情 维亚轩 shadow 2021-5-13 09:18:15
        $goods_discount = 0;
        $member_discount = 0;
        $shop_discount = 0;
        $the_user = M("users")->where("user_id = '".$user['user_id']."'")->find();

        foreach ($cartList as $k=>$val){
//			if($the_user['fenbu_id']!=0)
            if($val['stop_yijia'] == 1){
                $yijia=$val['member_goods_price']+yj_price($val['goods_id'],$val['member_goods_price'],$the_user['fenbu_id']);
            }else{
                $yijia=$val['member_goods_price'];
            }

//			else
//				$yijia=$val['member_goods_price'];
			
        	$cartList[$k]['goods_fee'] = sanwei($val['goods_num'] * $yijia);
        	$cartList[$k]['store_count']  = getGoodNum($val['goods_id'],$val['spec_key']); // 最多可购买的库存数量
            $anum += $val['goods_num'];
            
            // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
            if($selected == 1 && $val['selected'] == 0)
                continue;
            
            $cut_fee += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $yijia;
        	$total_price += $val['goods_num'] * $yijia;
        	$original_fee += $val['goods_num'] * $yijia;

            $cut_fee = sanwei($cut_fee);
            $total_price = sanwei($total_price);
            $original_fee = sanwei($original_fee);
            //计算商品的优惠信息 维亚轩 shadow 2019-5-13 08:58:53
            $the_goods = M("goods")->where("goods_id = '".$val['goods_id']."'")->find();
            if ($the_goods['prom_type'] > 0) {
                //1.判断是否有商品折扣
                $the_prom = get_goods_promotion($val['goods_id'],$user_id);
                $goods_discount += ($val['goods_price'] - $the_prom['price']) * $val['goods_num'];
            }else{
                //2.判断是否有会员折扣
                if ($the_user['discount'] < 1 && $the_user['discount'] > 0) {
                    $member_discount+= $val['goods_price'] * (1 - $the_user['discount']) * $val['goods_num'];
                }
            }
            if (($val['market_price'] - $val['goods_price']) > 0) {
                $shop_discount += ($val['market_price'] - $val['goods_price']) * $val['goods_num'];
            }
        }
        $total_price = array('original_fee'=>$original_fee,'total_fee' =>$total_price , 'cut_fee' => $cut_fee,'num'=> $anum,'goods_discount'=>$goods_discount,'member_discount'=>$member_discount,'shop_discount'=>$shop_discount); // 总计        
        setcookie('cn',$anum,null,'/');
        if($mode == 1) return array('cartList' => $cartList, 'total_price' => $total_price);
        return array('status'=>1,'msg'=>'','result'=>array('cartList' =>$cartList, 'total_price' => $total_price));
    }
	/*
	 计算购物车中某个店铺商品总价总和    by  tianxin  xiaojun
	*/
	
	function cart_store_price($user = array() , $session_id = '', $selected = 0,$store_id=0){
		
        $where = " 1 = 1 ";
        if($user[user_id])// 如果用户已经登录则按照用户id查询
        {
             $where .= " and user_id = $user[user_id] ";
             // 给用户计算会员价 登录前后不一样             
        }           
        else
        {
            $where .= " and session_id = '$session_id'";
            $user[user_id] = 0;
        }
		
		if($store_id){
			
			$where .= " and store_id = '$store_id'";
		}
		
        $cartList = M('Cart')->where($where)->select();  // 获取购物车商品 
        $total_price =  0;

        foreach ($cartList as $k=>$val){
			
            if($selected == 1 && $val['selected'] == 0){
                continue;
			}              
        	$total_price += $val['goods_num'] * $val['member_goods_price'];
        }

		return  	$total_price;	
	}

/**
 * 计算商品的的运费 
 * @param type $shipping_code 物流 编号
 * @param type $province  省份
 * @param type $city     市
 * @param type $district  区
 * @return int
 */
function cart_freight_mrlu($order_goods,$province,$city,$district,$weight)
{
    foreach ($order_goods as $key => $value) {
        //$newOrderGoods[$value['store_id']][] = $value;
        $orderGoodsPrice[$value['store_id']] += $value['shop_price'];
        $orderGoodsWeight[$value['store_id']] += $value['weight'];
    }
    
    foreach ($orderGoodsPrice as $key1 => $shopPrice) {
        // 默认免邮费
        $store_shipping_price[$key1] = 0;
        $total_shipping_fee = 0;
        // 超出该金额免运费， 店铺 设置 满多少 包邮 .
        $store_free_price = M('store')->where("store_id = $key1")->getField('store_free_price');
        if($store_free_price == 0 || $shopPrice < $store_free_price) {
            //$store_shipping_price[$key1] = $this->cart_freight2('yuantong',$province,$city,$district,$orderGoodsWeight[$key1]);
            $store_shipping_price[$key1] = $this->cart_freight2('yuantong',$province,$city,$district,$orderGoodsWeight[$key1]);
            $total_shipping_fee += $this->cart_freight2('yuantong',$province,$city,$district,$orderGoodsWeight[$key1]);
        }
    }
    $shippingPrice['total_shipping_fee'] = $total_shipping_fee;
    $shippingPrice['store_shipping_price'] = $store_shipping_price;
    //echo '<pre>';var_dump($shippingPrice);exit;
    return $shippingPrice;
}
/**
 * 计算商品的的运费 
 * @param type $shipping_code 物流 编号
 * @param type $province  省份
 * @param type $city     市
 * @param type $district  区
 * @return int
 */
function cart_freight2($shipping_code,$province,$city,$district,$weight)
{
    
    if($weight == 0) return 0; // 商品没有重量
    if($shipping_code == '') return 0;               
  
   // 先根据 镇 县 区找 shipping_area_id   
      $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$district}")->getField('shipping_area_id');
    
    // 先根据市区找 shipping_area_id
   if($shipping_area_id == false)    
      $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$city}")->getField('shipping_area_id');

   // 市区找不到 根据省份找shipping_area_id
   if($shipping_area_id == false)
        $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  ".C('DB_PREFIX')."shipping_area where shipping_code = '$shipping_code') and region_id = {$province}")->getField('shipping_area_id');

   // 省份找不到 找默认配置全国的物流费
   if($shipping_area_id == false)
   {           
        // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`           
       $shipping_area_id = M("ShippingArea")->where("shipping_code = '$shipping_code' and is_default = 1")->getField('shipping_area_id');
   }
   if($shipping_area_id == false)
       return 0;
   /// 找到了 shipping_area_id  找config       
   $shipping_config = M('ShippingArea')->where("shipping_area_id = $shipping_area_id")->getField('config');
   $shipping_config  = unserialize($shipping_config);
   $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;

   // 1000 克以内的 只算个首重费
   if($weight < $shipping_config['first_weight'])
   {          
       return $shipping_config['money'];     
   }
   // 超过 1000 克的计算方法 
   $weight = $weight - $shipping_config['first_weight']; // 续重
   $weight = ceil($weight / $shipping_config['second_weight']); // 续重不够取整 
   $freight = $shipping_config['money'] +  $weight * $shipping_config['add_money']; // 首重 + 续重 * 续重费       
   
   return $freight;  
}
  
    /**
     * 获取用户可以使用的优惠券
     * @param type $user_id  用户id 
     * @param type $coupon_id 优惠券id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function getCouponMoney($user_id, $coupon_id,$mode)
    {
        $couponlist = M('CouponList')->where("uid = $user_id and id = $coupon_id")->find(); // 获取用户的优惠券
        if(empty($couponlist)) {
            if($mode == 1) return 0;    
            return array('status'=>1,'msg'=>'','result'=>0);
        }            
        
        $coupon = M('Coupon')->where("id = {$couponlist['cid']}")->find(); // 获取 优惠券类型表
        $coupon['money'] = $coupon['money'] ? $coupon['money'] : 0;
       
        if($mode == 1) return $coupon['money'];
        return array('status'=>1,'msg'=>'','result'=>$coupon['money']);        
    }
    
    /**
     * 根据优惠券代码获取优惠券金额
     * @param type $couponCode 优惠券代码
     * @param type $order_momey Description 订单金额
     * return -1 优惠券不存在 -2 优惠券已过期 -3 订单金额没达到使用券条件
     */
    public function getCouponMoneyByCode($couponCode,$order_momey)
    {
        $couponlist = M('CouponList')->where("code = '$couponCode'")->find(); // 获取用户的优惠券
        if(empty($couponlist)) 
            return array('status'=>-9,'msg'=>'优惠券码不存在','result'=>'');
        $coupon = M('Coupon')->where("id = {$couponlist['cid']}")->find(); // 获取优惠券类型表
        if(time() > $coupon['use_end_time'])  
            return array('status'=>-10,'msg'=>'优惠券已经过期','result'=>'');
        if($order_momey < $coupon['condition'])
            return array('status'=>-11,'msg'=>'金额没达到优惠券使用条件','result'=>'');
        if($couponlist['order_id'] > 0)
            return array('status'=>-12,'msg'=>'优惠券已被使用','result'=>'');
        
        return array('status'=>1,'msg'=>'','result'=>$coupon['money']);
    }
    
    /**
     *  添加一个订单
     * @param type $user_id  用户id     
     * @param type $address_id 地址id
     * @param type $shipping_code 物流编号
     * @param type $invoice_title 发票
     * @param type $coupon_id 优惠券id
     * @param type $car_price 各种价格
     * @return type $order_id 返回新增的订单id
     */
public function addOrder($user_id,$address_id,$shipping_code,$invoice_title,$coupon_id = array(),$car_price,$user_note,$pay_code,$smoe_sn='')
    {
        // 仿制灌水 1天只能下 50 单  // select * from `tp_order` where user_id = 1  and order_sn like '20151217%' 
        //$order_count = M('Order')->where("user_id= $user_id and order_sn like '".date('Ymd')."%'")->count(); // 查找购物车商品总数量
        // if($order_count >= 50) 
        //     return array('status'=>-9,'msg'=>'一天只能下50个订单','result'=>'');
        
         // 插入订单 order
//        $address = M('UserAddress')->where("address_id = $address_id")->find();
		$users_dizi = M('users')->where("user_id = $user_id")->find();
		$wx_user = M('wx_user')->find();

		$jssdk = new \Mobile\Logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
       $Wxsend = new WxsendLogic();
       $time = time();
       $first_order_amount = 0;//首单金额
        $first_order_ids = '';//首单订单id

        //首单金额：查询用户是否第一次下单
        $is_order = M('Order')->where('user_id = '.$user_id)->find();

        
        // 循环添加订单 多少个商家添加多少个订单
        foreach($car_price['store_order_amount'] as $k => $v)
        {
            $first_order_amount = bcadd($first_order_amount,$car_price['store_goods_price'][$k]);//添加全部订单总额
                //$shipping = M('Plugin')->where("code = '{$shipping_code[$k]}'")->find();
                $order_sn = $this->get_order_sn(); // 获取生成订单号
                empty($master_order_sn) && ($master_order_sn = $this->get_order_sn()); // 主订单号
				
                // 用户使用余额
                $car_price['store_balance'][$k] = $car_price['store_balance'][$k] ? $car_price['store_balance'][$k] : 0;
                // 用户使用积分
                $car_price['store_point_count'][$k] = $car_price['store_point_count'][$k] ? $car_price['store_point_count'][$k] : 0;
                $auto_cancel_dates = M('config')->where(array('name'=>"auto_cancel_date"))->field("value")->find();
                $auto_cancel_date = $auto_cancel_dates['value'];  // 网站设置的订单过期时间（分钟）
				$cartList = M('Cart')
					->alias('a')
					->field('a.*,b.is_on_sale,b.goods_state,b.is_delete,b.fenbu_koudian,b.zd,b.prom_id')
					->join('ty_goods b on a.goods_id=b.goods_id')
					->where("a.store_id = $k and a.user_id = $user_id and a.selected = 1 and b.is_on_sale=1 and b.is_delete=0 and b.goods_state=1")->select();
					if(empty($cartList)){
						return array('status'=> '-1','msg'=>'订单异常，请联系客服。');
					}
				$store=M('store')->where('store_id='.$k)->find();
				if($store['store_state'] == 0){
				    	return array('status'=> '-1','msg'=>'商家：'.$store['store_name'].' 已经打样，请删除他的商品继续下单');
				}
				$danhaos.=$store['store_name'].':'.$order_sn.' ';
				$zong_price+=$car_price['store_order_amount'][$k];  //总价
				
				$sellers = M('seller a') //推送给商家
				->field('a.user_id,a.store_id,b.openid')
				->join('ty_users b on a.user_id=b.user_id','LEFT')
				->where("a.store_id = $k")->find();
				$UseConpon = 0;
                if(!empty($coupon_id[0])){
                    $UseConpon = M('CouponList')->where("id = $coupon_id[0]")->getField('cid');
                }

                $data = array(
                        'order_sn'         =>$order_sn, // 订单编号
                        'master_order_sn'  =>$master_order_sn, // 主订单号
                        'user_id'          =>$user_id, // 用户id
                        'consignee'        =>(string)$users_dizi['nickname'], // 收货人
//                        'province'         =>$address['province'],//'省份id',
//                        'city'             =>$address['city'],//'城市id',
//                        'district'         =>$address['district'],//'县',
//                        'twon'             =>$address['twon'],// '街道',
                        'address'          =>$users_dizi['company_address'],//'详细地址',
                        'mobile'           =>$users_dizi['mobile'],//'手机',
//                        'zipcode'          =>$address['zipcode'],//'邮编',
//                        'email'            =>$address['email'],//'邮箱',
                        'shipping_code'    =>'',//'物流编号', 
                        'shipping_name'    =>'众创织梦商城', //'物流名称',
                        'invoice_title'    =>$invoice_title, //'发票抬头',
                        'user_note'        =>$user_note, //'给卖家留言',
                        'goods_price'      =>$car_price['store_goods_price'][$k],//每个店铺的商品价格',
						'kou_price'      =>$car_price['kou_price'][$k], //平台收益, 
						'yijia_heji'      =>$car_price['yijia_heji'][$k], //溢价收益,
                        'shipping_price'   =>$car_price['store_shipping_price'][$k],//'物流价格',                
                        'user_money'       =>$car_price['store_balance'][$k], // 当前订单使用的余额数量
                        'coupon_price'     =>$car_price['store_coupon_price'][$k],//'使用优惠券',                        
                        'integral'         =>$car_price['store_point_count'][$k], // 使用的积分数量
                        'integral_money'   =>($car_price['store_point_count'][$k] / tpCache('shopping.point_rate')),//'使用积分抵多少钱',
                        'total_amount'     =>($car_price['store_goods_price'][$k] + $car_price['store_shipping_price'][$k]),// 订单总额 = 商品总价 + 物流费
                        'order_amount'     =>$car_price['store_order_amount'][$k],//'应付款金额',
                        'add_time'         =>time(), // 下单时间
                        'auto_cancel_date' =>time() + $auto_cancel_date * 60, // 下单未支付过期时间
                        'order_prom_id'    =>$car_price['store_order_prom_id'][$k],//'订单优惠活动id',
                        'order_prom_amount'=>$car_price['store_order_prom_amount'][$k],//'订单优惠活动优惠了多少钱',
                        'store_id'         =>$k,  // 店铺id
						'pay_code'         =>$pay_code,
						'fenbu_id'         =>$store['fenbu_id'],
						'ufenbu_id'        =>$users_dizi['fenbu_id'],
						'pay_name'         =>$car_price['pay_name'],
			            'same_order'       =>$smoe_sn,
			            'coupon_id'         =>$UseConpon,
                );


                
                //判断订单拼团订单是否能生成
				
                //$cartList = M('Cart')->where("store_id = $k and user_id = $user_id and selected = 1")->select();

                if($cartList[0]['prom_type'] == 101 && $cartList[0]['prom_id']>0){
                    $pint = M('pint')->find($cartList[0]['prom_id']);
                    $users = explode(',',$pint['users_id']);
                    if(in_array($cartList[0]['user_id'],$users)){
                        return array('status'=> '-1','msg'=>'您已存在该拼团');
                    }
                }
				
                             
				$mygoods='';
				$order_id = M("Order")->data($data)->add(); //主订单
                $first_order_ids .= $order_id.',';//记录首单订单id
				// $user_data = [
    //                 'user_id'          =>$user_id, // 用户id
    //                 'order_id'          =>$order_id, // 用户id
    //                 'price'             =>$car_price['store_order_amount'][$k]+$car_price['yijia_heji'][$k],
    //                 'store_id'         =>$k,  // 店铺id
    //                 'add_time'         =>time(), // 下单时间
    //                 'status'         =>0, // 下单时间
    //                 ];
    //             M('users_price')->add($user_data);
                $koudian = 0;
                $UseConpon = 0;
                if(!empty($coupon_id[0])){
                    $UseConpon = M('CouponList')->where("id = $coupon_id[0]")->getField('cid');
                }
                $goods_gzh_name = '';
                foreach($cartList as $key => $val)
                {
                   
                   $goods = M('goods')->where("goods_id =".$val['goods_id'])->find();

                    if(!empty($goods['fenbu_koudian'])){
                        $goods['fenbu_koudian'] = json_decode($goods['fenbu_koudian'],true);

                        foreach ($goods['fenbu_koudian'] as $kk=>$vv){
                            if($vv['fenbu_id'] == $users_dizi['fenbu_id']){
                                if(!empty($vv['fenbu_koudian'])){
                                    $goods['points'] = $vv['fenbu_koudian'];
                                    break;
                                }
                            }
                        }
                    }
                    //判断是否存在活动，存在活动是否有设置扣点
                    if($val['zd'] != 1){
                        if($val['prom_id'] > 0){
                            $prom = M('prom_goods')->where('id = '.$val['prom_id'].' and start_time <='.$time.' and end_time>='.$time.' and goods_key like "%'.$val['spec_key'].'%"')->getField('prom_kou');
                            if(!empty($prom)){
                                if($prom > 0){
                                    $goods['points'] = $prom;
                                }
                            }
                        }
                    }
        
                    $goods_gzh_name .= $val['goods_name'].',';
                    $koudian += ($val['member_goods_price'] * ($goods['points']/100))*$val['goods_num'];
					//$yijia=yj_price($val['goods_id'],$val['member_goods_price'],$users_dizi['fenbu_id']);
				   $yijia=$val['yijia'];
                   $data2['order_id']           = $order_id; // 订单id
                   $data2['goods_id']           = $val['goods_id']; // 商品id
                   $data2['goods_name']         = $val['goods_name']; // 商品名称
                   $data2['goods_sn']           = $val['goods_sn']; // 商品货号
                   $data2['goods_num']          = $val['goods_num']; // 购买数量
                   $data2['market_price']       = $val['market_price']; // 市场价
                   $data2['goods_price']        = $val['goods_price']; // 商品价
                   $data2['spec_key']           = $val['spec_key']; // 商品规格
                   $data2['spec_key_name']      = $val['spec_key_name']; // 商品规格名称
                   $data2['sku']                = $val['sku']; // 商品条码 
                   $data2['member_goods_price'] = $val['member_goods_price']; // 会员折扣价
                   $data2['cost_price']         = $goods['cost_price']; // 成本价
                   $data2['give_integral']      = $goods['give_integral']; // 购买商品赠送积分
                   $data2['prom_type']          = $val['prom_type']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠 , 4秒杀,5拼团
				   $data2['prom_msg']            = \get_goods_huodong($val['goods_id'],$val['spec_key'])['prom_msg'];
                   $data2['prom_id']            = $val['prom_id']; // 活动id
                   $data2['store_id']           = $val['store_id']; // 店铺id
                   $data2['distribut']          = $goods['distribut']; // 三级分销金额
                   //$data2['commission']         = M('goods_category')->where("id = ".$goods['cat_id3'])->getField('commission'); // 商品抽成比例
				   $data2['points']             = $goods['points'];
				   $data2['floating']           = $goods['floating'];
				   $data2['yijia']              = $yijia;
				   $data2['coupon_id']          = $UseConpon;
				   $data2['rank_status']        = $goods['p_status'];
				   $data2['full_status']        = $goods['prom_lock'];
				   
				   $mygoods.=$val['goods_id'].'|'.$val['goods_num'].'|'.$val['spec_key'].','; //记录产品。
                  M("order_goods")->data($data2)->add();
                  
                  if($goods['is_yanzhi'] == 1){
                      M('order_yanzhi')->add([
                          'goods_id'=>$val['goods_id'],
                          'order_id'=>$order_id,
                          'key'=>$val['spec_key'],
                          'price'=>$val['member_goods_price'],
                          'points'=>$goods['points'],
                          'yijia'=>$yijia,
                          'goods_num'=>$val['goods_num'],
                          'add_time'=>time()]
                          );
                  }
                  
				  if($yijia>0 && $users_dizi['fenbu_id']!=0){
				  M("order_yijia")->data([
					  'order_sn'=>$order_sn,
					  'order_id'=>$order_id,
					  'goods_id'=>$val['goods_id'],
					  'store_id'=>$val['store_id'],
					  'consignee'=>(string)$users_dizi['nickname'],
					  'spec_key'=>$val['spec_key'],
					  'goods_num'=>$val['goods_num'],
					  'y_price'=>$val['member_goods_price'],
					  'price'=>$yijia,
					  'fenbu_id'=>$users_dizi['fenbu_id'],
					  'add_time'=>\time()
				  ])->add(); //写入溢价分成表
				  }
				  
                   // 扣除商品库存  扣除库存移到 付完款后扣除
				   
                  $spec_kucun=M('spec_goods_price')->where("goods_id = ".$val['goods_id']." and `key`='".$val['spec_key']."'")->getField('store_count');
                  if($spec_kucun>=$val['goods_num']){
                  	M('spec_goods_price')->where("goods_id = ".$val['goods_id']." and `key`='".$val['spec_key']."'")->setDec('store_count',$val['goods_num']); // 商品减少库存
                  }
                   if($val['prom_type'] == 4){
                        M('order')->where(array('order_id'=>$order_id))->save(array('is_ms'=>1));
                   }
                } 
                 M('order')->where(array('order_id'=>$order_id))->save(array('kou_price'=>$koudian));
                // 记录订单操作日志
                logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$user_id,2,$mygoods);   
                
                // $openid = M('store')->where(['store_id'=>$k])->getField('store_openid');
                if($store['store_openid']){
                    if($store['bing_wx'] == 1){
                        $url = "pages/order_details/order_details?id=".$order_id.'&user_id='.$users_dizi['user_id'];
                        $wx_content = [];
                        $wx_content['touser'] = $store['store_openid'];
                        $wx_content['template_id'] = 'abjjdm52Y03djbYdS2aV8mqvxxXqGBynjgSpUysxlKI';
                        $wx_content['data'] = [
                            'character_string1'=>['value'=>$order_sn],
                            'amount2'=>['value'=>$car_price['store_order_amount'][$k].'元'],
                            'thing3'=>['value'=>$users_dizi['nickname']],
                            'time4'=>['value'=>date('Y-m-d H:i:s')],
                            'thing7'=>['value'=>mb_substr($goods_gzh_name,0,16).'..'],
                            ];
                        $wx_content['miniprogram'] = ['appid'=>'wx5427cce6d89fe90a','pagepath'=>$url];
                        $json = json_encode($wx_content);
                		$a = $jssdk->push_msg_mod($json);
                    }
                //     $sendData['order_sn'] = $order_sn;
                //     $sendData['nickname'] = $users_dizi['nickname'];
                //     $sendData['time'] = date('Y-m-d H:i:s');
                //     $sendData['address'] = $users_dizi['company_address'];
                //     $sendData['price'] = $car_price['store_order_amount'][$k].'元';
                //     $sendData['order_id'] = $order_id;
                //     $sendData['user_id'] = $users_dizi['user_id'];
                //     $Wxsend->sendSubscribeMessage($store['store_openid'],1,'ZBX1sxGm67KRi55iWAqFlLjWsAFAjujwCyLHcIcTwJs',$sendData);
                   
                }
               
                if($users_dizi['open_id']){
                    $sendData['order_sn'] = $order_sn;
                    $sendData['nickname'] = $users_dizi['nickname'];
                    $sendData['store_name'] = $store['store_name'];
                    $sendData['time'] = date('Y-m-d H:i:s');
                    $sendData['price'] = $car_price['store_order_amount'][$k].'元';
                    $sendData['order_id'] = $order_id;
                    $sendData['user_id'] = $users_dizi['user_id'];
                    $Wxsend->sendSubscribeMessage($users_dizi['open_id'],2,'ZBX1sxGm67KRi55iWAqFlOr8tjZNmkfAqSoaouNiXJM',$sendData);
                }
                
			  
                // 如果应付金额为0  可能是余额支付 + 积分 + 优惠券 这里订单支付状态直接变成已支付 
                if($data['order_amount'] == 0)
                {                        
                    update_pay_status($order_sn, 1);
                }
                if($data['order_amount'] == 0 || $pay_code == 'cod')
                {  
                    //拼团
                    if($val['prom_type'] == 101){
                        M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_type'=>101));
                        if($val['prom_id'] == 0){
                            //新开团
                            $ptg = M('Goods')->where(array('goods_id'=>$val['goods_id']))->find();
                            //判断拼团时间
                            if(time() > strtotime($ptg['pt_stop_time'])){
                                //去退款                                
                                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                                return array('status'=> -1,'msg'=>'1活动不存在或已结束');
                            }
                            $pintData = array(
                                'goods_id'          => $ptg['goods_id'],
                                'store_id'          => $ptg['store_id'],
                                'user_id'           => $user_id,
                                'users_id'          => $user_id,
                                'pint_price'        => $ptg['pt_price'],
                                'pint_star_time'    => time(),
                                'pint_stop_time'    => time()+3600*$ptg['pt_keep_time'],
                                'pint_user_num'     => $ptg['pt_man_num'],
                                'pint_status'       => 0,
                                'pint_user_num_now' => 1,
                                );
                            $pint_id = M('pint')->data($pintData)->add();
                            M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_id'=>$pint_id));
                            M('order_goods')->where(array('order_id'=>$order_id))->save(array('prom_id'=>$pint_id));
                            // echo '成功1';
                        }else{
                            //加入团
                            $pt = M('pint')->find($val['prom_id']);
                            $syrs = $pt['pint_user_num'] - $pt['pint_user_num_now'];
                            $sysj = $pt['pint_stop_time'] - time();
                            if(!$pt || $syrs<= 0 || $sysj<=0){
                                //去退款吧
                                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                                return array('status'=>-1,'msg'=>'活动不存在或已结束');
                            }
                            
                            $pintData = array(
                                'users_id'          => $pt['users_id'].','.$user_id,
                                'pint_status'       => 0,
                                'pint_user_num_now' => $pt['pint_user_num_now']+1,
                                );
                            M('pint')->where(array('pint_id'=>$pt['pint_id']))->data($pintData)->save();
                            M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_id'=>$val['prom_id']));
                            M('order_goods')->where(array('order_id'=>$order_id))->save(array('prom_id'=>$val['prom_id']));
                            $pit = M('pint')->find($pt['pint_id']);
                            if($pit['pint_user_num'] == $pit['pint_user_num_now']){
                                //拼团成功
                                M('pint')->where(array('pint_id'=>$pt['pint_id']))->data(array('pint_status'=>1))->save();
                                $pt_numed = M('order_goods')->where(array('goods_id'=>$pt['goods_id'],'prom_type'=>'101','prom_id'=>$pt['pint_id']))->getField('COUNT(goods_num)');
                            	M('goods')->where(array('goods_id'=>$pt['goods_id']))->setINc('pt_numed',$pt_numed);
                            }
                        }
                    }
                }else{
                    if($val['prom_type'] == 101){
                        M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_type'=>101));
                        if($val['prom_id'] == 0){
                            //新开团
                            $ptg = M('Goods')->where(array('goods_id'=>$val['goods_id']))->find();
                            //判断拼团时间
                            if(time() > strtotime($ptg['pt_stop_time'])){
                                //去退款                                
                                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                                return array('status'=> -1,'msg'=>'3该拼团活动不存在或已结束');
                            }
                        }else{
                            //加入团
                            $pt = M('pint')->find($val['prom_id']);
                            $syrs = $pt['pint_user_num'] - $pt['pint_user_num_now'];
                            $sysj = $pt['pint_stop_time'] - time();
                            if(!$pt || $syrs<= 0 || $sysj<=0){
                                //去退款吧
                                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                                return array('status'=>-1,'msg'=>'4该拼团活动不存在或已结束');
                            }                         
                            M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_id'=>$pt['pint_id']));
                            M('order_goods')->where(array('order_id'=>$order_id))->save(array('prom_id'=>$pt['pint_id']));
                            $pit = M('pint')->find($pt['pint_id']);

                        }
                    }
                }
                if(!empty($coupon_id[$k])){
                	// 2修改优惠券状态
                	$data3['uid'] = $user_id;
                	$data3['order_id'] = $order_id;
                	$data3['use_time'] = time();
                	M('CouponList')->where("id = {$coupon_id[$k]}")->save($data3);
                	$cid = M('CouponList')->where("id = $coupon_id[$k]")->getField('cid');
                	M('Coupon')->where("id = $cid")->setInc('use_num'); // 优惠券的使用数量加一
                }

                // 3 扣除积分 扣除余额
                M('Users')->where("user_id = $user_id")->setDec('pay_points',$car_price['store_point_count'][$k]); // 用户的积分减 
                M('Users')->where("user_id = $user_id")->setDec('user_money',$car_price['store_balance'][$k]); // 用户的余额减         
               
                // 4 清空购物车
                M('Cart')->where("store_id = $k and user_id = $user_id and selected = 1")->delete();

                // 5 记录log 日志
                $data4['user_id'] = $user_id;
                $data4['user_money'] = -$car_price['store_balance'][$k];
                $data4['pay_points'] = -$car_price['store_point_count'][$k];
                $data4['change_time'] = time();
                $data4['desc'] = '下单消费';
                $data4['order_sn'] = $order_sn;
                $data4['order_id'] = $order_id;    
                // 如果使用了积分或者余额才记录
                ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);     

				//分销开关全局
				$order = M("Order")->where("order_id = $order_id")->find();	
				//echo   APP_PATH.'Common/Logic/DistributLogic.class.php';
				if(file_exists(APP_PATH.'WXAPI/Logic/DistributLogic.class.php'))
				{
					
					$distributLogic = new \WXAPI\Logic\DistributLogic;
					$distributLogic->rebate_log($order); // 生成分成记录
				} 
					 
           }

//        if ($user_id == 1230){
//            M('users')->where('user_id = '.$user_id)->save([
//                first_order_amount => $first_order_amount,
//                first_order_time => time(),
//                first_order_ids => $first_order_ids
//            ]);
//        }
           
        //平台券的抵扣
        if(count($coupon_id) == 1 && !empty($coupon_id[0])){
            $data3['uid'] = $user_id;
            $data3['master_order_sn'] = $master_order_sn;
            $data3['use_time'] = time();
            M('CouponList')->where("id = {$coupon_id[0]}")->save($data3);
            $cid = M('CouponList')->where("id = $coupon_id[0]")->getField('cid');
            M('Coupon')->where("id = $cid")->setInc('use_num'); // 优惠券的使用数量加一
        }

        //首单金额：写入数据
        if (!$is_order){
            M('users')->where('user_id = '.$user_id)->save([
                first_order_amount => $first_order_amount,
                first_order_time => time(),
                first_order_ids => $first_order_ids
            ]);
        }
 

// 		M('Users')->where("user_id = $user_id")->setField(['last_sale'=>time()]); //last_sale更新
// 		// 如果有微信公众号 则推送一条消息到微信 
// 		if($users_dizi['openid'])
// 		{
// 		$wx_content='{
// 		    "touser":"'.$users_dizi['openid'].'",
// 		    "template_id":"hCr9aeTks1S3sVkp1ILxsYpoetKKMj2G6oOUdQt3w2I",
// 		    "url":"https://shop.lswjsc.com/index.php/Mobile/Index/",
// 		    "miniprogram":{
// 		      "appid":"wx7c609f6efbc804de",
// 		      "pagepath":"pages/member/index/index"
// 		    },          
// 		    "data":{
// 		            "first": {
// 		                "value":"您的订单提交成功！",
// 		                "color":"#173177"
// 		            },
// 		            "keyword1":{
// 		                "value":"'.$danhaos.'",
// 		                "color":"#173177"
// 		            },
// 					"keyword2":{
// 						"value":"￥'.$zong_price.'",
// 						"color":"#fa5151"
// 					},
// 		            "remark":{
// 		                "value":"感谢您对我们的支持！",
// 		                "color":"#173177"
// 		            }
// 		    }
// 		}';

// 		$jssdk->push_msg_mod($wx_content);
// 		}
        update_user_level($user_id);
        return array('status'=>1,'msg'=>'提交订单成功','result'=>$master_order_sn); // 返回新增的订单id
    }
	
    /**
     * 查看购物车的商品数量
     * @param type $user_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function cart_count($user_id,$mode = 0){
        $count = M('Cart')->where("user_id = $user_id and selected = 1")->count();
        if($mode == 1) return  $count;
        
        return array('status'=>1,'msg'=>'','result'=>$count);         
    }
        
   /**
    * 获取商品团购价
    * 如果商品没有团购活动 则返回 0
    * @param type $attr_id
    * $mode 0  返回数组形式  1 直接返回result
    */
   public function get_group_buy_price($goods_id,$mode=0)
   {
       $group_buy = M('GroupBuy')->where("goods_id = $goods_id and ".time()." >= start_time and ".time()." <= end_time ")->find(); // 找出这个商品                      
       if(empty($group_buy))       
            return 0;
       
        if($mode == 1) return $group_buy['groupbuy_price'];
        return array('status'=>1,'msg'=>'','result'=>$group_buy['groupbuy_price']);       
   }  
   
   /**
    * 用户登录后 需要对购物车 一些操作
    * @param type $session_id
    * @param type $user_id
    */
   public function login_cart_handle($session_id,$user_id)
   {
	   if(empty($session_id) || empty($user_id))
	     return false;
        // 登录后将购物车的商品的 user_id 改为当前登录的id            
        M('cart')->where("session_id = '$session_id'")->save(array('user_id'=>$user_id));                    
        
        $Model = new \Think\Model();
        // 查找购物车两件完全相同的商品
        $cart_id_arr = $Model->query("select id from `__PREFIX__cart` where user_id = $user_id group by  goods_id,spec_key having count(goods_id) > 1");
        if(!empty($cart_id_arr))
        {
            $cart_id_arr = get_arr_column($cart_id_arr, 'id');
            $cart_id_str = implode(',', $cart_id_arr);
            M('cart')->delete($cart_id_str); // 删除购物车完全相同的商品
        }
   }
   /**
    * 获取订单 order_sn
    */
   public function get_order_sn()
   {
   	// 保证不会有重复订单号存在
   	while(true){
   		$order_sn = date('YmdHis').rand(1000,9999); // 订单编号
   		$order_sn_count = M('order')->where("order_sn = '$order_sn' or master_order_sn = '$order_sn'")->count();
   		if($order_sn_count == 0)
   			break;
   	}
   	return $order_sn;
   }
}